import {
    createRouter,
    // hash
    createWebHashHistory,
    // history
    createWebHistory
} from 'vue-router'
import Login from "@/pages/Login.vue"
import Index from "@/pages/index/Index.vue"
import Dashboard from "@/pages/main/Dashboard.vue"
import NotFound from "@/pages/404.vue"
import {baseStore} from '@/store/baseStore.js'
import sysManager from './sysManager.js'
import i18n from '@/language/index'
import nativeLanguage from "@/router/nativeLanguage.js";
import images from "@/router/image.js";
import ai from "@/router/ai.js";
import model from "@/router/model.js"

const t = i18n.global.t
const routes = [
    {
        path: "/",
        name: 'router.login',
        component: Login,
        meta: {
            // 标识为框架组件
            frame: true,
            // 是否认证，true 不认证
            auth: false
        }
    },
    // 404页面配置
    {
        path: '/:pathMatch(.*)*',
        mame: 'router.notFound',
        component: NotFound,
        meta: {
            frame: true,
            auth: true
        }
    },
    // 业务路由一定要在这里写(顺序)，一旦改变
    {
        path: '/index',
        component: Index,
        redirect: '/dashboard',
        meta: {
            frame: true,
            auth: true,
        },
        children: [
            {
                path: '/dashboard',
                name: 'Dashboard',
                icon: 'House',
                component: Dashboard,
                meta: {
                    ln: 'router.dashboard',
                    auth: true,
                    // 页面需要被缓存
                    keepAlive: true,
                    menu: true
                },
            },
            sysManager,
            nativeLanguage,
            images,
            ai,
            // model
        ]
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.ENV_BASE_PATH),
    routes,
})

/**
 * 得到业务系统路由
 * @returns {RouteRecord[]}
 */
router.getBusinessRouter = function () {
    let ro = router.getRoutes().filter(item => !item.meta.frame).map(item => {
        return {
            "path": item.path,
            "name": item.name,
            "meta": item.meta,
            "children": item.children
        }
    })
    return ro
}

router.getTree = function () {
    return router.getRoutes().filter(item => item.meta.menu)
}

router.tabsState = ref([])
/**
 * 给 tabsState 添加路由
 */
router.beforeResolve(async to => {
    let path = router.getBusinessRouter()
    path.forEach(item => {
        if (item.path !== to.path) {
            return
        }
        if (router.tabsState.value.some((i) => i.path === to.path)) {
            return
        }
        router.tabsState.value.push(to)
    })
})

router.beforeEach((to, from, next) => {
    let token = baseStore().token
    if (to.meta.auth && !token) {
        next({path: "/"})
        return
    }
    // window.document.title = t('header.title')
    // 如果用户未能验证身份，则 `next` 会被调用两次
    next()
})

export default router
